package net.gazhi.delonix.grac.init;

import net.gazhi.delonix.core.dao.Dao;
import net.gazhi.delonix.core.init.InitService;
import net.gazhi.delonix.grac.AC_TB;
import net.gazhi.delonix.grac.entity.gru.Role;
import net.gazhi.delonix.grac.entity.gru.User;
import net.gazhi.delonix.grac.entity.gru.UserDir;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 初始化超级管理员
 * 
 * @author Jeffrey Lin
 */
public class InitSuperUserService implements InitService {

	private static final Log logger = LogFactory.getLog(InitSuperUserService.class);

	@Autowired
	private Dao dao;

	@Override
	public void init() throws Exception {
		logger.info("正在初始化 [SueperUser]...");
		this.initRole();
		this.initUserDir();
		this.initUser();
		logger.info("初始化 [SueperUser] 完成。");
	}

	public void initRole() {
		Role role = dao.get(Role.class, 1L);
		if (role == null) {
			dao.createSQLQuery("insert into " + AC_TB.ac_role + "(id, name_zh, name_en, show_order, is_disabled) values (1, '超级管理员', 'Super Administrator', '!TOP', 0)").executeUpdate();
		}
		dao.createSQLQuery("delete ra from " + AC_TB.ac_role_action + " ra left join " + AC_TB.ac_action + " a on ra.action_id=a.id where a.id is null").executeUpdate();
		dao.createSQLQuery(
				"insert into " + AC_TB.ac_role_action + " (role_id, action_id) select 1 role_id, a.id action_id from " + AC_TB.ac_action + " a left join " + AC_TB.ac_role_action
						+ " ra on ra.role_id=1 and ra.action_id=a.id  where ra.action_id is null").executeUpdate();
	}

	public void initUserDir() {
		UserDir dir = dao.get(UserDir.class, 1L);
		if (dir == null) {
			dao.createSQLQuery("insert into " + AC_TB.ac_user_dir + "(id, name_zh, name_en, show_order, full_id, full_order) values (1, '所有用户', 'All Users', 1, 1, 1)").executeUpdate();
		}
	}

	public void initUser() {
		User user = dao.get(User.class, 1L);
		if (user == null) {
			String psw = new BCryptPasswordEncoder().encode("abc123");
			dao.createSQLQuery(
					"insert into " + AC_TB.ac_user + "(id, dir_id, name_zh, name_en, locale, show_order, login_name, login_psw, is_active) "
							+ "values (1, 1, '超级管理员', 'Super Administrator', 'zh', 0, 'sa' , '" + psw + "', 1)").executeUpdate();
		}
		if (dao.createSQLQuery("select 1 from " + AC_TB.ac_user_role + " where user_id=1 and role_id=1").uniqueResult() == null) {
			dao.createSQLQuery("insert into " + AC_TB.ac_user_role + "(user_id, role_id) values (1,1)").executeUpdate();
		}
	}

}
